package com.ry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ry.dao.CommentDao;
import com.ry.model.dto.CommentDTO;
import com.ry.model.entity.Comment;
import com.ry.service.CommentServcie;
import com.ry.service.UserService;
import com.ry.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2021-11-11 21:08
 **/
@Service
public class CommentServcieImpl implements CommentServcie {
    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UserService userService;

    @Override
    public void add(CommentDTO commentDTO) {
        Comment entity = new Comment();
        entity.setId(commentDTO.getId());
        entity.setContent(commentDTO.getContent());
        entity.setStateId(commentDTO.getStateId());
        entity.setFromUserId(commentDTO.getFromUserId());
        entity.setToUserId(commentDTO.getToUserId());
        entity.setCreateTime(LocalDateTime.now().toString());

        commentDao.insert(entity);
    }

    @Override
    public void delete(Integer id) {
        commentDao.deleteById(id);
    }

    @Override
    public List<CommentDTO> selectByStateId(Integer stateId) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("state_id",stateId);
        List<Comment> comments = commentDao.selectList(wrapper);
        List<CommentDTO> info = comments.stream().map(entity -> {
            CommentDTO commentDTO = new CommentDTO();
            commentDTO.setId(entity.getId());
            commentDTO.setContent(entity.getContent());
            commentDTO.setStateId(entity.getStateId());
            commentDTO.setFromUserId(entity.getFromUserId());
            commentDTO.setToUserId(entity.getToUserId());
            commentDTO.setCreateTime(entity.getCreateTime());
            commentDTO.setFromUsername(userService.getUserById(entity.getFromUserId()).getNickname());
            commentDTO.setToUsername(userService.getUserById(entity.getFromUserId()).getNickname());

            return commentDTO;
        }).collect(Collectors.toList());


        return info;
    }
}
